﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Linq;

namespace ORM.Test
{
    public static  class  AttributeExtend
    {
        public static string GetTableName(this Type type)
        {
            if (type.IsDefined(typeof(TableNameAttribute),true))
            {
                var tableNameAttribute = (TableNameAttribute)type.GetCustomAttributes(typeof(TableNameAttribute), true)[0];
                return tableNameAttribute.GetName();
            }
            else
            {
                return type.Name;
            }
           
        }
        public static string GetColName(this PropertyInfo prop)
        {
            if (prop.IsDefined(typeof(TableNameAttribute), true))
            {
                var tableNameAttribute = (TableNameAttribute)prop.GetCustomAttributes(typeof(TableNameAttribute), true)[0];
                return tableNameAttribute.GetName();
            }
            else
            {
                return prop.Name;
            }

        }

        public static IEnumerable<PropertyInfo> NotKey(this Type type)
        {
            return type.GetProperties().Where(t=>!t.IsDefined(typeof(KeyAttribute),true));
        }

        public static PropertyInfo GetKey(this Type type)
        {
            PropertyInfo[] props = type.GetProperties().Where(t => t.IsDefined(typeof(KeyAttribute), true)).ToArray();
            return props!=null && props.Length>0?props[0]:null;
        }

        public static string GetMappingName(this MemberInfo type)
        {
            if (type.IsDefined(typeof(AbstractMapNameAttribute), true))
            {
                var attribute = type.GetCustomAttribute<AbstractMapNameAttribute>();
                return attribute.GetName();
            }
            else
            {
                return type.Name;
            }
        }
    }
}
